#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>

int main(int argc, char const *argv[])
{
    int fd_old = -1;
    int fd_new = -1;
    struct stat stStat;
    char * buf;

    if(argc != 3)
    {
        printf("Usage: %s <old-file> <new-file>\n", argv[0]);
        return -1;
    }

    /*1. 打开老文件  */
    fd_old = open(argv[1], O_RDONLY);
    if(fd_old < 0)
    {
        perror("open");
        return -2;
    }

    /* 2. 确定老文件的大小 */
    if(fstat(fd_old, &stStat) < 0) 
    {
        perror("fstat");
        return -3;
    }

    /* 3. 隐射老文件 */
    buf = mmap(NULL, stStat.st_size, PROT_READ, 
    MAP_SHARED, fd_old, 0);
    if(buf == MAP_FAILED)
    {
        perror("mmap");
        return -4;
    }

    /* 4. 创建新文件 */
    fd_new = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP
| S_IWGRP | S_IROTH | S_IWOTH);
    if(fd_new < 0)
    {
        perror("open");
        return -5;
    }

    if(write(fd_new, buf, stStat.st_size) != stStat.st_size)
    {
        perror("write");
        return -6;
    }

    close(fd_old);
    close(fd_new);

    
    return 0;
}
